//
//  CPDownloadTools.m
//  Teacher App
//
//  Created by collegepre on 16/7/28.
//  Copyright © 2016年 collegepre. All rights reserved.
//

#import "CPDownloadTools.h"
#import "SSZipArchive.h"
#import <CPSecurityTools/CPSecurityTools.h>
#import "NSString+DCDownload.h"

#import "DCOSSDDownloadOpration.h"
#import "CPDownloadInfo.h"

#import "CPCourseZipSecurityInfo.h"
#import "NSString+DCDownload.h"

// coreData管理工具
#import "CPCoreDataModelManager.h"
#import "NSObject+CoreDataKeyValues.h"
#import "CPCoursePakageUnzipAndDecryptTools.h"
#import "NSString+DCDownload.h"

#import "DCDownloadOprationManager.h"



@interface CPDownloadTools()
/**
// *  所有下载信息的管理
// */
//@property (nonatomic, strong) NSMutableArray *allDownloadOpration;

/**
 *  正在下载
 */
@property (nonatomic, strong) NSMutableArray *downloadingOpration;
//
///**
// *  下载完成
// */
//@property (nonatomic, strong) NSMutableArray *downloadedOpraion;
//
/**
 *  等待下载
 */
@property (nonatomic, strong) NSMutableArray *waitingDownloadOpration;


@property (nonatomic, strong) CPCoreDataModelManager *coreDataManager;

@property (nonatomic, strong) NSOperationQueue *downloadOprationQueue;

@property (nonatomic, strong) DCDownloadOprationManager *downloadManager;

@property (nonatomic, strong) DCOSSDDownloadOpration *ossDownloadOpration;
@end

@implementation CPDownloadTools

- (NSMutableArray *)downloadingOpration{
    if (!_downloadingOpration) {
        _downloadingOpration = [NSMutableArray array];
    }
    return _downloadingOpration;
}

- (NSMutableArray *)waitingDownloadOpration{
    if (!_waitingDownloadOpration) {
        _waitingDownloadOpration = [NSMutableArray array];
    }
    return _waitingDownloadOpration;
}


- (DCOSSDDownloadOpration *)ossDownloadOpration{
    if (!_ossDownloadOpration) {
        _ossDownloadOpration = [DCOSSDDownloadOpration shareOSSDownloadOpration];
    }
    return _ossDownloadOpration;
}

- (DCDownloadOprationManager *)downloadManager{
    if (!_downloadManager) {
        _downloadManager = [DCDownloadOprationManager managerWithIdentifier:@"NormalDownload"];
        _downloadManager.maxDownloadingCount = 2;
    }
    return _downloadManager;
}

+ (instancetype)shareDownloadTools{
    return [[self alloc] init];
}

- (instancetype)init{
    if (self = [super init]) {
        _maxQueueNum = 3;
    }
    return self;
}


- (void)setMaxQueueNum:(NSInteger)maxQueueNum{
    _maxQueueNum = maxQueueNum;
    if (maxQueueNum<=1) {
        _maxQueueNum = 2;
    }
}

- (CPCoreDataModelManager *)coreDataManager{
    if (!_coreDataManager) {
        _coreDataManager = [CPCoreDataModelManager sharedInstanceWithStoreName:@"CPDownloadManager"];
    }
    return _coreDataManager;
}



- (CPDownloadInfo *)downloadInfoWithCourseJson:(NSDictionary *)dict{
    
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"osskey = %@ AND downloadURL = %@ AND destinationPath = %@",dict[@"osskey"],dict[@"downloadURL"],dict[@"destinationPath"]];
    NSArray *results = [self.coreDataManager searchWithentityForObjectClass:[CPDownloadInfo class] predicate:pred sortDescriptors:nil];
    if (results.count) {
        return [results firstObject];
    }else{
    CPDownloadInfo *info = [CPDownloadInfo cp_objectWithKeyValues:dict coreDataManager:self.coreDataManager];
    return info;
    }
}


/**
 *  根据传的下载信息直接下载课件包
 *
 *  @param downloadInfo     下载信息
 *  @param donwloadProgress 进度回调
 *  @param complition       完成回调
 *  @param unzipProgress    解压进度回调
 *  @param decryptProgress  解密进度回调
 */
- (void)cp_downloadCoursePakageZipWithDonloadJson:(NSDictionary *)dict progress:(CPDownloadProgress)donwloadProgress donwloadComplition:(CPDonwloadCompliction)complition unzipProgress:(CPDownloadUnzipProgress)unzipProgress decryptMediaProgress:(CPDownloadUnzipProgress)decryptProgress{
    
    CPDownloadInfo *downloadInfo = [self downloadInfoWithCourseJson:dict];
    
    
    [self cp_downloadCoursePakageZipWithDonloadInfo:downloadInfo progress:^(NSInteger currentLength, NSInteger totalLength, float pro) {
        donwloadProgress(currentLength,totalLength,pro);
    } donwloadComplition:^(NSError *error) {
        complition(error);
    } unzipProgress:^(float pro) {
        unzipProgress(pro);
    } decryptMediaProgress:^(float pro) {
        decryptProgress(pro);
    }];
}

/**
 *  根据传的下载信息直接下载课件包
 *
 *  @param downloadInfo     下载信息
 *  @param donwloadProgress 进度回调
 *  @param complition       完成回调
 *  @param unzipProgress    解压进度回调
 *  @param decryptProgress  解密进度回调
 */
- (void)cp_downloadCoursePakageZipWithDonloadInfo:(CPDownloadInfo *)downloadInfo progress:(CPDownloadProgress)donwloadProgress donwloadComplition:(CPDonwloadCompliction)complition unzipProgress:(CPDownloadUnzipProgress)unzipProgress decryptMediaProgress:(CPDownloadUnzipProgress)decryptProgress{
    
//      self.progressBlock = donwloadProgress;
//      self.donloadCompliction = complition;
//      self.unziprogress = unzipProgress;
//      self.decryptMediaProgress =decryptProgress;

    // 如果正在下载的的数量小于3个可以接着下载
       
     __block typeof(self) weakSelf = self;
    // 开始下载任务
    DCOSSDDownloadOpration *ossDownloadOpration = [DCOSSDDownloadOpration shareOSSDownloadOpration];
        [ossDownloadOpration CPOSSDownloadWithDownloadInfo:downloadInfo downloadProgress:^(NSInteger currentLength, NSInteger totalLength, float pro) {
            //进度回调
            donwloadProgress(currentLength,totalLength,pro);
        } complition:^(NSError *error) {

            complition(error);
            if (!error) {
                [CPCoursePakageUnzipAndDecryptTools unzipWithzipdownloadInfo:downloadInfo unzipProgress:^(float pro) {
                    unzipProgress(pro);
                    if (pro == -1.0f) {
                        // 下载失败删除包文件
                        [[NSFileManager defaultManager] removeItemAtPath:downloadInfo.destinationPath error:nil];
                        [[NSFileManager defaultManager] removeItemAtPath:downloadInfo.unzipPath error:nil];
                    }
                } decryptProgress:^(float pro) {
                    decryptProgress(pro);
                    if (pro == -1.0f) {
                        // 下载失败删除包文件
                        [[NSFileManager defaultManager] removeItemAtPath:downloadInfo.destinationPath error:nil];
                        [[NSFileManager defaultManager] removeItemAtPath:downloadInfo.unzipPath error:nil];
                    }
                }];
            }else{
                // 下载失败删除包文件
                [[NSFileManager defaultManager] removeItemAtPath:downloadInfo.destinationPath error:nil];
                [[NSFileManager defaultManager] removeItemAtPath:downloadInfo.unzipPath error:nil];
            }
        }];
    
        // 将下载信息保存到数据库
        [weakSelf.coreDataManager saveContext];
}

/**
 *  下载完成之后移除下载信息并清空CoreData数据
 *
 *  @param downloadInfo 下载信息
 */
- (void)removeDownloadOprationWithDownloadInfo:(CPDownloadInfo *)downloadInfo{
    
    [self.coreDataManager deletdeleteObject:downloadInfo];
}

/**
 *  从CoreData数据中重启未完成下载的项目 ，一初始化的时候就会调用
 */
- (void)reloadDownloadOprationFromCoreData{
    NSArray *arr =  [self.coreDataManager searchWithentityForObjectClass:[CPDownloadInfo class] predicate:nil sortDescriptors:nil];
    if (arr.count) { // 如果能查询到数据 则直接返回
        for (CPDownloadInfo *info in arr)
        {
            [self cp_downloadCoursePakageZipWithDonloadInfo:info progress:^(NSInteger currentLength, NSInteger totalLength, float pro) {
                
            } donwloadComplition:^(NSError *error) {
         
            } unzipProgress:^(float pro) {
                
            } decryptMediaProgress:^(float pro) {
                
            }];
        }
    }
}



#pragma mark--老的下载方法
- (void)cp_downloadLessonWithURL:(NSString *)url toDestinationPath:(NSString *)destinationPath unzipPath:(NSString *)unzipPath header:(NSString *)header key:(NSString *)key zipMD5:(NSString *)md5 progress:(DCDownloadOprationResuming)progress state:(DCDownloadStateChangeBlock)statechange donwloadComplition:(CPDonwloadCompliction)complition{
    self.donloadCompliction = complition;
     [self.downloadManager  download:url toDestinationPath:destinationPath progress:^(NSInteger curentBytes, NSInteger TotalBytes, DCDownloadOpration *downloadopration) {
        if (progress) {
            progress(curentBytes,TotalBytes,downloadopration);
        }
        if (curentBytes == TotalBytes) {
            NSString *fileMD5 = [NSString fileMD5withFilePath:destinationPath readingDataLength:1024 * 8];
            if(md5.isNotEmpty){
                if ([fileMD5 isEqualToString:md5]) {
                    [self unzipWithzipPath:destinationPath unzipPath:unzipPath header:header key:key];
                }else{
                    NSError *error = [NSError errorWithDomain:@"1002" code:1002 userInfo:@{@"errorinfo":@"MD5值验证不通过"}];
                    self.donloadCompliction(error);
                }
            }else{
                [self unzipWithzipPath:destinationPath unzipPath:unzipPath header:header key:key];
            }
        }
    } state:^(DCDownloadState state, NSString *file, NSError *error, DCDownloadOpration *downloadopration){
        
    }];
    
    
}

- (void)unzipWithzipPath:(NSString *)zipPath unzipPath:(NSString *)unzipPath header:(NSString *)header key:(NSString *)key
{
    NSFileManager *mgr = [NSFileManager defaultManager];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [SSZipArchive unzipFileAtPath:zipPath toDestination:unzipPath progressHandler:^(NSString *entry, unz_file_info zipInfo, long entryNumber, long total) {
            
        } completionHandler:^(NSString *path, BOOL succeeded, NSError *error) {
            if (!succeeded) {
                self.donloadCompliction(error);
                [mgr removeItemAtPath:zipPath error:nil];
                [mgr removeItemAtPath:unzipPath error:nil];
            }else
            {
                [mgr removeItemAtPath:zipPath error:nil];
                if (header.isNotEmpty && key.isNotEmpty)
                {
                    [[CPMediaDecryptTool defaultDecryptTool] decodeWithsuperFilePath:unzipPath headerCodeLength:header keyCodeValue:key progress:^(float progress) {
                        
                    } complition:^(NSError *error) {
                        
                        if (error) {
                            [mgr removeItemAtPath:zipPath error:nil];
                            [mgr removeItemAtPath:unzipPath error:nil];
                            self.donloadCompliction(error);
                        }else{
                            self.donloadCompliction(nil);
                        }
                    }];
                    
                }else{
                    self.donloadCompliction(nil);
                }
            }
        }];
    });
}
@end
